import { commonSendMessageApi } from '@/api/common';
import { REG_PHONE } from '@/constants/reg';
export function useCaptcha() {
	const { endLoading, loading, startLoading } = useLoading();
	const { count, isCounting, start } = useCountDownTimer(60);
	const label = useMemo(() => {
		let text = '获取验证码';

		const countingLabel = `${count}s后重新获取`;

		if (loading) {
			text = '';
		}

		if (isCounting) {
			text = countingLabel;
		}

		return text;
	}, [count]);

	function isPhoneValid(phone: string) {
		if (phone.trim() === '') {
			return false;
		}

		if (!REG_PHONE.test(phone)) {
			return false;
		}

		return true;
	}
	async function getCaptcha(phone: string) {
		const valid = isPhoneValid(phone);

		if (!valid || loading) {
			return;
		}

		startLoading();

		// await new Promise(resolve => {
		// 	setTimeout(resolve, 500);
		// });
		const res = await commonSendMessageApi({ phone });

		if (res.success) {
			window.$message.info('验证码已发送到您的手机');
		}

		start();

		endLoading();
	}

	return {
		getCaptcha,
		isCounting,
		label,
		captchaLoading: loading
	};
}
